package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.OutCome;
import com.yegs.jltqc.VO.QcStock;
import com.yegs.jltqc.config.ConcurentCache;
import com.yegs.jltqc.dao.OutComeRepository;
import com.yegs.jltqc.dao.QcStockRepository;
import com.yegs.jltqc.service.OutComeService;
import com.yegs.jltqc.service.QcStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OutStockServiceImpl implements QcStockService {

    @Autowired
    private QcStockRepository qcStockRepository;

    @Override
    public QcStock save(QcStock qcStock) {
        qcStock.setCreateTime(new Date());
        qcStock.setCreateBy( ConcurentCache.getUserName());
        return qcStockRepository.save(qcStock);
    }

    @Override
    public List<QcStock> list() {
        return qcStockRepository.findAll();
    }

    @Override
    public QcStock get(Long id) {
        return qcStockRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        qcStockRepository.deleteById(id);
    }

    @Override
    public Page<QcStock> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return qcStockRepository.findAll(request);
        }
        return qcStockRepository.findQcStocksByName(query.getName(), request);
    }

    @Override
    public Long getNext(Long id) {
        if(id == null){
            QcStock qcStock = qcStockRepository.findFirstByOrderByIdDesc();
            if(qcStock != null) {
                return qcStock.getId();
            }
        }
        QcStock qcStock = qcStockRepository.findFirstByIdIsAfter(id);
        if(qcStock == null){ qcStock = qcStockRepository.findFirstByOrderByIdDesc(); }
        if(qcStock != null){
            return qcStock.getId();
        }
        return null;
    }

    @Override
    public Long getLast(Long id) {
        if(id == null){
            QcStock qcStock = qcStockRepository.findFirstByOrderByIdDesc();
            if(qcStock != null) {
                return qcStock.getId();
            }
        }
        else{
            QcStock qcStock = qcStockRepository.findFirstByIdBeforeOrderByIdDesc(id);
            if(qcStock == null){ qcStock = qcStockRepository.findFirstByOrderById(); }
            if(qcStock != null){
                return qcStock.getId();
            }
        }
        return null;
    }
}
